const API_BASE_URL = 'http://localhost:8080/api';

// 登录API
export const login = async (data) => {
  try {
    console.log('发送登录请求:', data);
    const response = await fetch(`${API_BASE_URL}/auth/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    });
    console.log('响应状态:', response.status);
    if (!response.ok) {
      const errorText = await response.text();
      console.error('响应错误详情:', errorText);
      throw new Error(`登录失败: ${response.status} - ${errorText}`);
    }
    const result = await response.json();
    console.log('登录响应结果:', result);
    if (result.success) {
      return result;
    } else {
      throw new Error(result.message || '登录失败');
    }
  } catch (error) {
    console.error('登录错误:', error);
    throw error;
  }
};

// 获取用户信息
export const getUserInfo = async () => {
  try {
    const token = localStorage.getItem('token');
    const response = await fetch(`${API_BASE_URL}/auth/userinfo`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
    if (!response.ok) throw new Error('获取用户信息失败');
    const result = await response.json();
    if (result.success) {
      return result;
    } else {
      throw new Error(result.message || '获取用户信息失败');
    }
  } catch (error) {
    console.error('获取用户信息错误:', error);
    throw error;
  }
};

// 退出登录
export const logout = async () => {
  try {
    const token = localStorage.getItem('token');
    const response = await fetch(`${API_BASE_URL}/auth/logout`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
    if (!response.ok) throw new Error('退出登录失败');
    const result = await response.json();
    if (result.success) {
      return result;
    } else {
      throw new Error(result.message || '退出登录失败');
    }
  } catch (error) {
    console.error('退出登录错误:', error);
    throw error;
  }
};

// 注册API
export const register = async (data) => {
  try {
    const response = await fetch(`${API_BASE_URL}/auth/register`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    });
    if (!response.ok) throw new Error('注册失败');
    const result = await response.json();
    if (result.success) {
      return result;
    } else {
      throw new Error(result.message || '注册失败');
    }
  } catch (error) {
    console.error('注册错误:', error);
    throw error;
  }
};

export default { login, getUserInfo, logout, register };